﻿var vm = this.lookupViewModel();
var controller = this.lookupController();
//草稿ID
var draftId = PAI.Global.getUrlData('draftId');
//复制表单ID
var formDataId = PAI.Global.getUrlData('formDataId');
var controller = this.lookupController();
var destInstId = controller.destInstId;
var procInstId = controller.procInstId;
//ExpenseType的值
var expenseType = this.lookupViewModel().get('NebulogyForm.GeneralInformation.ExpenseType');
//流程状态
var viewStatus = this.analysis.status;
var emp = PAI.Global.getAccount().employee;

//给流程状态赋值
this.lookupViewModel().set('NebulogyForm.companySection.status', viewStatus);
//暂时隐藏
ref.MaterialNumberCJLR.hide();

if (ref.datagrid2.getColumns()[5].getEditor) {
    ref.datagrid2.getColumns()[5].getEditor().setMaxValue(1000000000);
}

//所属公司
var jlrOrganization = emp.ext_jlrOrganization;
ref.jlrOrganization.setValue(jlrOrganization);
//页面上显示发起单号，发起时间，单前节点审批人
Ext.PAIRest.request({
    url: 'formActivity/currentProcInst',
    ns: PAI.application.userServerUrl,
    method: 'POST',
    data: {
        destInstId: destInstId || '',
        procInstId: procInstId || ''
    },
    success: function (data) {
        if (data.currentActivitys && data.currentActivitys.length > 0) {
            controller.currentActivity = data.currentActivitys[0].activityName; //节点名称
            controller.currentActivityId = data.currentActivitys[0].activityId;//节点ID
            var activity = controller.currentActivity; //节点名称
            //定义变量报存节点id
            vm.set('NebulogyForm.nodeName', controller.currentActivityId);
            //获取当前审批人
            var item, no, cache = [];
            for (var i = 0; i < data.currentActivitys[0].empList.length; i++) {
                item = data.currentActivitys[0].empList[i];
                no = item.employeeNo || '空';
                if (item.defaultLanguage == 'en') {
                    cache.push(item.lastName + ' ' + item.firstName + '(' + no + ')');
                }
                else {
                    cache.push(item.lastName + item.firstName + '(' + no + ')');
                }
            }
            // vm.set('NebulogyForm.HeadInfo.CurrentApprover', cache.join(';'));
            ref.currentApprover.setValue(cache.join(';'));
        }
    },
    failure: function (data) {
    }
});


//暂时禁用费用类型.
//ref.ExpenseType.setReadOnly(true);
var activity = vm.get('NebulogyForm.companySection.activity');

//OUV Type在FA节点和Enquire 需要根据PR Type禁用一些选项.
var isEnquiryOrFaActivity = false;

//隐藏文件grid的删除按钮.(已经添加的不让删除)
function hideDelete(file, fileLength) {
    ref[file].on('afterlayout', function () {
        var fileEl = ref[file].getEl();
        var trList = fileEl.dom.querySelectorAll('tr');
        //获取到所有的tr
        if (trList.length) {
            for (var i = 0; i < trList.length; i++) {
                if (i <= fileLength - 1) {
                    //获取当前tr下面所有的td 然后把最后一个td给隐藏.
                    var tdList = trList[i].querySelectorAll('td');
                    tdList[tdList.length - 1].style = 'display:none;';
                }
            }
        }
    });
}

//重新提交的时候允许多选框编辑
if (this.analysis.status == 'resubmit') {
    ref.SpecialApprovers.setReadOnly(false);

    var isInquiryCall = vm.get('NebulogyForm.isInquiryCall');
    if (isInquiryCall == 1) {
        isEnquiryOrFaActivity = true;
        var fieldNameList = ['file7', 'file8', 'datagrid2', 'datagrid3', 'datagrid4', 'UKGLCode', 'UKCostCenter', 'PRName', 'prTarget', 'PreCommit', 'datetime3', 'datetime4', 'Purchasing'];
        Ext.each(fieldNameList, function (fieldName) {
            if (ref[fieldName].getColumns) {

                //enquire后Horizon/Project X Allocation子表 可新增 删除
                if (!['datagrid3'].includes(fieldName)) {
                    var gridColumns = ref[fieldName].getColumns();
                    //隐藏删除按钮,除了文件
                    if (!fieldName.startsWith('file')) {
                        gridColumns[gridColumns.length - 1].hide();
                    }

                    var button = ref[fieldName].down('button');
                    if (button) {
                        button.hide();
                    }
                }
            }
        });
        //禁用其他所有控件.
        for (var ctrName in ref) {
            if (!fieldNameList.includes(ctrName) && ref[ctrName].xtype != 'section') {
                if (ref[ctrName].setReadOnly) {
                    ref[ctrName].setReadOnly(true);
                } else {
                    console.log(ctrName);
                }
            }
        }
        var file7List = vm.get('NebulogyForm.file7') || [];
        var file8List = vm.get('NebulogyForm.file8') || [];

        //因为隐藏文件删除按钮会导致数据不加载.所以要把数据清空 在回写.
        ref.file8.store.removeAll();
        ref.file8.store.loadData(file8List);
        ref.approverDesc.setReadOnly(false);

        hideDelete('file7', file7List.length);
        hideDelete('file8', file8List.length);

        //需要把采购Item中的originalTotalPrice重新赋值.
        var store = ref.datagrid2.getStore();

        Ext.each(store.data.items, function (r) {
            r.data.originalTotalPrice = r.get('TotalPrice');

            //Enquiry 之后的采购项内的 价格差 (PriceDiffer) 需要清零
            r.data.PriceDiffer = 0;
            r.commit();
        });

        //公司分摊子表 也需要设置一个 原始值
        Ext.each(ref.datagrid3.store.data.items, function (r) {
            r.data.originalTotalPrice = r.get('Cost');
            r.commit();
        });

        //不是OUV才判断 POType 是否可以编辑
        if (expenseType != '4') {
            var poType = vm.get('NebulogyForm.FinanceInformation.PRType');

            if (poType == 'normal') {
                ref.PRType.setReadOnly(false);
            }
        }
    }
}
//如果是重新提交或者草稿或者复制表单
if (draftId || viewStatus == 'resubmit' || formDataId != "") {
    var url = PAI.application.serviceUrl;
    var itemAccount = "";
    var jaConst = "";
    var lrConst = "";
    var budgetItems = this.lookupViewModel().get('NebulogyForm.companySection.budgetItem');
    Ext.PAIRest.request({
        ns: PAI.application.serviceUrl,
        url: 'jlr-rest/api/budgetRelationItem/getBudgetItemParentNode',
        method: "POST",
        async: false,
        data: {
            "budgetItemId": budgetItems
        },
        success: function (data) {
            if (data.budgetRelationItemF05RespS01 !== null || data.budgetRelationItemF05RespS02 !== null || data.budgetRelationItemF05RespS03 !== null) {
                var pa = [];
                for (var i = 0; i < data.budgetRelationItemF05RespS01.length; i++) {
                    pa.push({
                        ID: data.budgetRelationItemF05RespS01[i].id,
                        ProjectActivity: data.budgetRelationItemF05RespS01[i].projectActivty
                    });
                }

                vm.set('NebulogyForm.ProjectActivityList', pa);

                for (var x = 0; x < data.budgetRelationItemF05RespS02.length; x++) {
                    itemAccount = data.budgetRelationItemF05RespS02[x].glAccount;
                }

                for (var j = 0; j < data.budgetRelationItemF05RespS03.length; j++) {
                    jaConst = data.budgetRelationItemF05RespS03[j].costCenterJa;
                    lrConst = data.budgetRelationItemF05RespS03[j].costCenterLr;
                }
            }

            ref.datagrid4.JACostCenter = jaConst;
            ref.datagrid4.LRCostCenter = lrConst;
        },
        failure: function (jsondata) {
        }
    });

    //给GLaccount赋值
    this.lookupViewModel().set('NebulogyForm.GeneralInformation.Account', itemAccount);
}
ref.sectioncols52.hide();
ref.VSVCheck.setReadOnly(true);
ref.Check.setReadOnly(true);

ref.financeMemoCJLR.hide();
ref.financeMemoJLRC.hide();
ref.CIP.hide();

if (vm.get('NebulogyForm.AssetEmpId') == emp.id) {
    ref.CIP.show();
}

//FA之后的节点.
var activiNameList = ['Corporate_FME_Finance_LL6', 'Corporate_FME_Finance_LL5', 'Corporate_FME_CFO', 'FME_Dummy_LL3', 'Corporate_FME_LL2', 'Corporate_OUV_Finance_LL6', 'Corporate_OUV_Finance_LL5', 'Corporate_OUV_CFO', 'OUV_Dummy_LL3', 'Corporate_OUV_LL2', 'Corporate_Tooling_Finance_LL6', 'Corporate_Tooling_Finance_LL5', 'Corporate_Tooling_CFO', 'Tooling_Dummy_LL3', 'Corporate_Tooling_LL2', 'Corporate_SE_Finance_LL6', 'Corporate_SE_Finance_LL5', 'Corporate_SE_CFO', 'SE_Dummy_LL3', 'Corporate_SE_LL2', 'UK审核', 'Asset审核', 'Buyer'];

if (this.analysis.status == 'launch') {

    //赋值给部门和人员
    Ext.PAIRest.request({
        url: 'orgEmployeeRel/listOrganizationObjByEmployeeObjId',
        method: 'POST',
        data: {
            bId: PAI.Global.getAccount().employee.id,
            objFields: [{
                exp: "$." + PAI.Global.getLanguage(),
                name: "displayName",
                type: "json"
            }],
            relFields: [{
                "name": "aId"
            }]
        },
        success: function (json) {
            if (!Ext.isEmpty(json.data)) {
                vm.set('NebulogyForm.GeneralInformation.Department', json.data[0].basic.displayName);
                vm.set('NebulogyForm.GeneralInformation.DepartmentId', json.data[0].ext.aId);
            }
        }
    });
} else if (this.analysis.status == 'approval') {
    if (vm.get('NebulogyForm.bizModelId')) {
        //审批视图加载的时候需要更新数据到结构化表中.因为Enquiry无法获取到准确的数据.
        Ext.PAIRest.request({
            ns: PAI.application.serviceUrl,
            url: 'user-service/api/formDesign/instanceFormSave',
            method: "POST",
            async: false,
            data: {
                "formDataIds": vm.get('NebulogyForm.bizModelId')
            },
            success: function (data) {
            },
            failure: function (jsondata) { }
        });
    }

    ref.file7.setReadOnly(true);
    ref.file8.setReadOnly(true);

    //if (['BuyerBrforeAsset', 'Buyer'].includes(activity)) {
    //    var file8List = vm.get('NebulogyForm.file8') || [];

    //    ref.file8.setReadOnly(false);
    //    hideDelete('file8', file8List.length);
    //}

    //记录FA节点及其后面节点的操作登录人ID.
    if (activity.endsWith('FA') || activiNameList.includes(activity)) {
        var approverIdList = vm.get('NebulogyForm.approverIdList') || [];

        if (!Ext.Array.contains(approverIdList, emp.id)) {
            approverIdList.push(emp.id);
        }

        vm.set('NebulogyForm.approverIdList', approverIdList);
    }

    //根据申请人职级判断第一个审批节点
    var employeesRank = vm.get('NebulogyForm.employeesRank');
    if (employeesRank == 'GSR' || employeesRank == 'others') {
        if (activity == 'Corporate_FME_LL6' || activity == 'Corporate_OUV_LL6' || activity == 'Corporate_Tooling_LL6' || activity == 'Corporate_SE_LL6') {
            ref.approverDesc.notBlank = true;
        }
    } else {
        if (activity == 'Corporate_FME_LL5' || activity == 'Corporate_OUV_UsedbyLL5' || activity == 'Corporate_Tooling_LL5' || activity == 'Corporate_SE_LL5') {
            ref.approverDesc.notBlank = true;
        }
    }

    if (activity.startsWith('Asset')) {
        ref.CIP.show();
        ref.CIP.setAllowBlank(false);
        ref.CIP.setReadOnly(false);

        vm.set('NebulogyForm.AssetEmpId', emp.id);

    } else if (activity == 'Corporate – OUV-FA' || activity == 'Corporate -Tooling-FA' || activity == 'Corporate - SE-FA' || activity == 'Corporate – FME-FA') {
        isEnquiryOrFaActivity = true;
        ref.PreCommit.setReadOnly(false);
        ref.SpecialApprovers.setReadOnly(false);
        ref.sectioncols52.show();
        ref.VSVCheck.setReadOnly(false);

        var isCheck = (vm.get('NebulogyForm.FinanceInformation.VSVCheck') || {})[1] == 1;

        ref.Check.setReadOnly(!isCheck);
        ref.Check.setAllowBlank(!isCheck);

        ref.UKGLCode.setReadOnly(false);
        ref.UKCostCenter.setReadOnly(false);
        ref.UKGLCode.setAllowBlank(false);
        ref.UKCostCenter.setAllowBlank(false);
        ref.approverDesc.notBlank = true;

        //只有FA节点可以修改数据,但是不能修改勾选过.
        var specialApprovers = vm.get('NebulogyForm.ApproversSelection.SpecialApprovers');
        for (var k in specialApprovers) {
            Ext.each(ref.SpecialApprovers.items.items, function (ctr) {
                if (ctr.inputValue == k && specialApprovers[k] == 1) {
                    ctr.setReadOnly(true);
                }
            });
        }

        var jlrOrganization = vm.get('NebulogyForm.GeneralInformation.jlrOrganization');
        if (jlrOrganization == "JLR" || jlrOrganization == "JLR(LHF)" || jlrOrganization == "1" || jlrOrganization == "ISE" || jlrOrganization == "PS") {
            ref.financeMemoJLRC.show();
            ref.financeMemoCJLR.hide();
        } else if (jlrOrganization == "CJLR" || jlrOrganization == "Chery") {
            ref.financeMemoCJLR.show();
            ref.financeMemoJLRC.hide();
        } else {
            ref.financeMemoCJLR.hide();
            ref.financeMemoJLRC.hide();
        }

    } else if (activity.startsWith('UK')) {
        ref.file8.setReadOnly(false);
        var ukCrossCharge = vm.get('NebulogyForm.FinanceInformation.UKCrossCharge');
        if (ukCrossCharge == 'JLRCUK' || ukCrossCharge == 'UKJLRC') {
            ref.file7.setReadOnly(false);
        }
    } else if (activity.endsWith('SpecialApprovers2')) {
        ref.sectioncols52.show();
        ref.VSVCheck.setReadOnly(false);

        var isCheck = (vm.get('NebulogyForm.FinanceInformation.VSVCheck') || {})[1] == 1;

        ref.Check.setReadOnly(!isCheck);
        ref.Check.setAllowBlank(!isCheck);
    } else {
        ref.SpecialApprovers.setReadOnly(true);
    }

    //所有的审批页面上只有Purchase Item默认展开，Company Allocation，Brand Allocation，Project X和审批人部分折叠
    ref.VendorInformation.collapsed = true;
    ref.CompanyAllocation.collapsed = true;
    ref.BrandAllocationJLRC.collapsed = true;
    ref.ApproversSelection.collapsed = true;
}

//流程结束需要显示SAP PR No,Current Approver
var formhistory = view.down('formhistory');
var isComplete = false;
if (formhistory) {
    var store = formhistory.down('grid').getStore();

    store.on('load', function (store, records) {
        Ext.each(records, function (record) {
            if (record.get('finalAction') == 'PA_ProcComplete') {
                isComplete = true;
                var prType = vm.get('NebulogyForm.FinanceInformation.PRType');
                if (prType == 'normal') {
                    ref.sapPRNo.show();
                }
                ref.currentApprover.hide();
                ref.sectioncols52.show();
                if (vm.get('NebulogyForm.AssetEmpId')) {
                    ref.CIP.show();
                }
            }
        });
    });
}
var vendorCordeArr = [];

if (formData.VendorInformation) {

    Ext.each(formData.VendorInformation, function (record) {
        vendorCordeArr.push({
            code: record.Code,
            name: record.Code
        });
    });

    var editor2 = ref.datagrid2.getColumns()[2];

    if (editor2.getEditor) {
        editor2.getEditor().getStore().loadData(vendorCordeArr);
    }
}

// 给表格的Total 赋默认值
setTimeout(function () {
    function getTotal(records, totalField, grossField) {

        var amoutCount = [],
            grossAmount = [];

        Ext.each(records, function (record) {
            amoutCount.push(record.get('TotalPrice') || 0);
            grossAmount.push(record.get('GrossAmount') || 0);
        });
        if (amoutCount.length) {
            ref[totalField].setValue(Ext.util.Format.number(parseFloat(amoutCount.reduce(function (a, b) {
                return (a + b);
            }).toFixed(2)), '0,000.00'));
            ref[grossField].setValue(Ext.util.Format.number(parseFloat(grossAmount.reduce(function (a, b) {
                return (a + b);
            }).toFixed(2)), '0,000.00'));
        } else {
            ref[totalField].setValue('0.00');
            ref[grossField].setValue('0.00');
        }
    }

    getTotal(ref.datagrid2.store.data.items, 'pi1', 'tga1');

    //Company ALlocation 需要单独赋值.
    //数据变更 需要同步Total
    var amoutObj = {
        JLRC: 0,
        CJLR: 0,
        LRE: 0
    };

    Ext.each(ref.datagrid3.store.data.items, function (record) {
        var company = record.get('Company');

        if (record.get('Cost')) {
            amoutObj[company] = parseFloat((amoutObj[company] + record.get('Cost')).toFixed(2));
        }
    });
    var layoutColumns = 5;
    for (var c in amoutObj) {
        if (c) {
            if (amoutObj[c]) {
                ref['total' + c].show();
                ref['total' + c].setValue(Ext.util.Format.number(amoutObj[c], '0,000.00'));
            } else {
                layoutColumns--;
                ref['total' + c].hide();
            }
        }
    }
    ref.section44.layoutColumns = layoutColumns;
}, 200);

//FA节点之后需要展示VSV
var approverIdList = vm.get('NebulogyForm.approverIdList') || [];

if (activiNameList.includes(activity) || approverIdList.includes(emp.id)) {
    ref.sectioncols52.show();
    if (this.analysis.status == 'approval') {
        ref.VSVCheck.setReadOnly(false);

        var isCheck = (vm.get('NebulogyForm.FinanceInformation.VSVCheck') || {})[1] == 1;

        ref.Check.setReadOnly(!isCheck);
        ref.Check.setAllowBlank(!isCheck);
    }
}

//如果是launch 和resubmit视图,则需要把PurchaseItems的默认追加到下面的字表.
if (viewStatus == 'launch' || viewStatus == 'resubmit') {
    var store = ref.datagrid2.getStore();
    var d = [];
    //Company Allocation下拉框的数据需要重新绑定一次.
    Ext.each(store.data.items, function (record) {
        d.push({
            name: record.get('DescriptionOfSuppliesServices'),
            code: record.get('DescriptionOfSuppliesServices')
        });
    });

    ref.datagrid3.getColumns()[0].getEditor().store.loadData(d);
    ref.datagrid4.getColumns()[0].getEditor().store.loadData(d);
    ref.datagrid5.getColumns()[0].getEditor().store.loadData(d);
}